package controllers

import (
	"classmates/models"
	"encoding/json"
	"net/http"
	"strings"
	"time"

	beego "github.com/beego/beego/v2/server/web"
	"github.com/gorilla/websocket"
)

// RecordsController operations for Classmates
type RecordsController struct {
	beego.Controller
}

func (c *RecordsController) Records() {
	c.TplName = "records.html"
}

func (c *RecordsController) Fill() {
	c.TplName = "fill.html"
}

func (c *RecordsController) Choujiang() {
	c.TplName = "choujiang.html"
}

// signIn ...
// @Title 签到
// @Description 考勤签到
// @Param	body		body 	models.Records	true		"body for Records content"
// @Success 200 {object} models.Records
// @Failure 403 :id is empty
// @router /signIn [post]
func (c *RecordsController) SignIn() {

	var v models.Records

	result := make(map[string]interface{})
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err != nil {
		result["code"] = 0
		result["data"] = err.Error()
		c.Data["json"] = result
		c.ServeJSON()
		return
	}
	if models.AllCourse[v.Course] == nil {
		result["code"] = 0
		result["data"] = "没有这个课程"
		c.Data["json"] = result
		c.ServeJSON()
		return
	}

	snObj := c.Ctx.Input.GetData("sn")
	v.Sn = snObj.(string)
	v.Createtime = time.Now()
	v.Now = time.Now().Format("200601021504")
	v.Now = v.Now[:len(v.Now)-1]
	v.CourseCn = models.AllCourse[v.Course].CourseCn
	target := models.AllClassMates[v.Sn]
	if target == nil {

		result["code"] = 0
		result["data"] = v.Sn + "查无此学号"
		c.Data["json"] = result
		c.ServeJSON()
		return
	}

	if _, err := models.AddRecords(&v); err != nil {
		if strings.Contains(err.Error(), "Duplicate") {
			result["code"] = 0
			result["data"] = "十分钟内不能重复提交"
			c.Data["json"] = result
		} else {
			result["code"] = 0
			result["data"] = err.Error()
			c.Data["json"] = result
		}
		c.ServeJSON()
		return

	}
	result["code"] = 1
	result["user"] = models.AllClassMates[v.Sn]
	c.Data["json"] = result
	c.ServeJSON()

}

// GetAll ...
// @Title 查询
// @Description get Classmates
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Classmates
// @Failure 403
// @router /query [get]
func (c *RecordsController) GetAll() {
	snObj := c.Ctx.Input.GetData("sn")
	snStr := snObj.(string)
	var query = make(map[string]string)
	query["sn"] = snStr
	result := make(map[string]interface{})
	records, err := models.GetStudentRecords(query, 0, 10000)
	if err != nil {
		result["code"] = 0
		result["data"] = err.Error()
		c.Data["json"] = result
	} else {
		result["code"] = 1
		result["data"] = records
		c.Data["json"] = result
	}
	c.ServeJSON()
	return

}

var choujiangChan = make(chan string, 100)
var choujiangMap map[string]string = make(map[string]string)

// GetAll ...
// @Title 参与抽奖
// @Description 参与抽奖
// @Success 200 {object} models.Classmates
// @Failure 403
// @router /canyuChoujiang [get]
func (c *RecordsController) CanyuChoujiang() {
	snObj := c.Ctx.Input.GetData("sn")
	snStr := snObj.(string)
	result := make(map[string]interface{})
	if models.AllClassMates[snStr] == nil {
		result["code"] = 0
		result["data"] = "请检查学号：" + snStr + "是否登记"
		c.Data["json"] = result
		c.ServeJSON()
		return
	}
	choujiangMap[snStr] = models.AllClassMates[snStr].Name
	choujiangChan <- snStr
	result["code"] = 1
	result["sn"] = snStr
	result["name"] = choujiangMap[snStr]
	c.Data["json"] = result
	c.ServeJSON()
}

var upgrader = websocket.Upgrader{
	// 允许跨域请求，这里只是示例，实际生产环境需谨慎设置
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// GetAll ...
// @Title 载入抽奖人
// @Description 载入抽奖人
// @Success 200 {object} models.Classmates
// @Failure 403
// @router /loadPersons [get]
func (c *RecordsController) LoadPersons() {
	w := c.Ctx.ResponseWriter.ResponseWriter
	conn, err := upgrader.Upgrade(w, c.Ctx.Request, nil)
	if err != nil {
		c.Data["json"] = err
		c.ServeJSON()
		return
	}
	defer conn.Close()
	conn.WriteMessage(websocket.TextMessage, []byte(""))
	for sn, name := range choujiangMap {
		err = conn.WriteMessage(websocket.TextMessage, []byte(name+"<br>"+sn))
		if err != nil {

			c.Data["json"] = err
			c.ServeJSON()
			return
		}
	}

	for {
		sn := <-choujiangChan
		person := models.AllClassMates[sn]
		// 将接收到的消息回显给客户端
		err = conn.WriteMessage(websocket.TextMessage, []byte(person.Name+"<br>"+person.Sn))
		if err != nil {
			c.Data["json"] = err
			c.ServeJSON()
			return
		}
	}
}

// GetAll ...
// @Title clearChoujiang
// @Description 删除参与投票的人员
// @Success 200 {object} models.Classmates
// @Failure 403
// @router /clearChoujiang [get]
func (c *RecordsController) ClearChoujiang() {
	result := make(map[string]interface{})
	choujiangMap = make(map[string]string)
	result["code"] = 1
	result["data"] = choujiangMap
	c.Data["json"] = result
	c.ServeJSON()
}
